package com.shyroke.daydayzhuansvc.util;

import org.joda.time.DateTime;

import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;

/**
 * 日期处理类
 * @author youhj
 * @date 2019/7/3 0003 下午 12:51
 */
public class DateUtils {

    public static final String fullTime="yyyy-MM-dd HH:mm:ss";
    public static final String ymdTime="yyyy-MM-dd";

    public static Object format(Date date, String format) {
        if(date == null){
            return null;
        }
        DateTime dateTime = new DateTime(date);
        return dateTime.toString(format);
    }

    public static Date getByDateStr(String date) throws Exception{
        SimpleDateFormat unix_time=new SimpleDateFormat(fullTime);
        return unix_time.parse(date);
    }

    /**
     * 将时间戳转为字符串
     * @param timestamp
     * @return
     */
    public static String getTimestampDate(String timestamp) {
        String str;
        SimpleDateFormat unix_time=new SimpleDateFormat(fullTime);
        str=unix_time.format(new Date(Long.valueOf(timestamp)));

        return str;
    }

    /**
     * 获取今天年月日
     * @return
     */
    public static String getToday() {
        Date date = new Date();
        SimpleDateFormat format =new SimpleDateFormat(ymdTime);
        return format.format(date);
    }

    /**
     * 获取N天前日期
     * @param i
     * @return
     */
    public static String getBefore(int i) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE,-i);
        Date date = cal.getTime();
        SimpleDateFormat format =new SimpleDateFormat(ymdTime);
        return format.format(date);
    }

    /**
     * 某个时间减去N小时
     * @param date
     * @param hour
     * @return
     */
    public static Date sub(Date date, int hour) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.HOUR,-hour);
        return calendar.getTime();
    }

    /**
     * 获取本月第一天
     * @return
     */
    public static String getMonthBegin() {
        SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_MONTH, 1);
        return myFormatter.format(cal.getTime());
    }

    /**
     * 获取本月最后一天
     * @return
     */
    public static String getMonthEnd() {
        SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DATE, 1);
        //主要就是这个roll方法
        cal.roll(Calendar.DATE, -1);
        return myFormatter.format(cal.getTime());
    }


    public static void main(String[] args) {
        System.out.println(getMonthBegin());
        System.out.println(getMonthEnd());
    }
}
